import { createRouter, createWebHashHistory } from "vue-router";

import login from "../pages/login.vue";
import console from "../pages/console.vue"
import orderlist from "../pages/orderlist.vue";
import index from "../pages/index.vue";
import { useGlobalStore } from "../store";
import Detail from "../pages/detail.vue";

const router = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/',
            redirect: '/console/index'
        },
        {
            path: '/login',
            name: "login",
            component: login,
        },
        {
            path: '/console',
            component: console,
            children: [
                {
                    path: 'orderlist',
                    component: orderlist
                },
                {
                    path: 'index',
                    component: index
                },
                {
                    path: 'detail/:id',
                    component: Detail
                }
            ]
        }
    ]
})

router.beforeEach((to, from, next) => {
    window.console.log(from);
    
    window.console.log("to.path ==>", to.path);
    if (to.path === '/login') {
        next();
    } else {
        const store = useGlobalStore();
        window.console.log("store.token ==>", store);
        if (!store.token || store.tokenExpired * 1000 < Date.now()) {
            next('/login')
        } else {
            next();
        }
    }
})

export {router};